/*
 * 文件名：CTMSInitServlet.java
 * 版权：Copyright 2006-2011 AsiaInfo Tech. Co. Ltd. All Rights Reserved. 
 * 描述： CTMSInitServlet.java
 * 修改人：齐鹏飞
 * 修改时间：2011-9-5
 * 修改内容：新增
 */
package com.fengxing.ams.pub.manager;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.fengxing.ams.pub.constants.ConfigurationID;
import com.fengxing.ams.pub.constants.ServletInitSwitch;
import com.fengxing.ams.pub.util.LogUtil;
import com.fengxing.ams.pub.util.ResourceUtil;

/**
 * CTMS初始化Servlet
 * <p>
 * CTMS初始化Servlet： 1.加载配置文件
 * <p>
 * 
 * <pre>
 * </pre>
 * 
 * @author 齐鹏飞
 * @version CTMS V100R001 2011-9-5
 * @since CTMS V100R001C01
 */
public class CTMSInitServlet extends HttpServlet {

	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(CTMSInitServlet.class);

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1545921608062263326L;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void init() throws ServletException {
		if (logger.isDebugEnabled()) {
			LogUtil.debug(logger, "init() - start"); //$NON-NLS-1$
		}

		this.initConfig(this.getServletConfig());

		if (logger.isDebugEnabled()) {
			LogUtil.debug(logger, "init() - end"); //$NON-NLS-1$
		}
	}

	private void initConfig(ServletConfig config) {
		
		ServletContext sc = config.getServletContext();
		
		WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
		SpringContextManager.initContext(applicationContext);
		
		if (logger.isDebugEnabled()) {
			LogUtil.debug(logger, "initConfig(ServletConfig) - start"); //$NON-NLS-1$
		}

		// 开关关闭
		if (!isInit(ServletInitSwitch.INIT_CONFIG_SWITCH, config)) {
			if (logger.isDebugEnabled()) {
				LogUtil.debug(logger, "initConfig(ServletConfig) - end"); //$NON-NLS-1$
			}
			return;
		}

		if (logger.isDebugEnabled()) {
			LogUtil.debug(logger, "initConfig(ServletConfig) - end"); //$NON-NLS-1$
		}
	}

	private boolean isInit(String switchName, ServletConfig config) {
		if (logger.isDebugEnabled()) {
			LogUtil.debug(logger, "isInit(String, ServletConfig) - start"); //$NON-NLS-1$
		}

		boolean returnboolean = "true".equalsIgnoreCase(config
				.getInitParameter(switchName));
		if (logger.isDebugEnabled()) {
			LogUtil.debug(logger, "isInit(String, ServletConfig) - end"); //$NON-NLS-1$
		}
		return returnboolean;
	}
}
